import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import viteCompression from 'vite-plugin-compression'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import externalGlobals from 'rollup-plugin-external-globals'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import importToCDN, { autoComplete } from 'vite-plugin-cdn-import'


export default defineConfig({
  plugins: [
    vue(),
    VueSetupExtend(),
    importToCDN({
      modules: [
        autoComplete('vue'),
        autoComplete('axios'),
        {
          name: 'element-plus',
          var: 'ElementPlus',
          path: 'https://cdn.jsdelivr.net/npm/element-plus@2.1.3/dist/index.full.min.js',
          css: 'https://cdn.jsdelivr.net/npm/element-plus@2.1.3/dist/index.min.css'
        },
        {
          name: 'vue-router',
          var: 'VueRouter',
          path: 'https://cdn.jsdelivr.net/npm/vue-router@4.0.14/dist/vue-router.global.prod.min.js'
        },
        {
          name: 'vue-demi',
          var: 'VueDemi',
          path: 'https://cdn.jsdelivr.net/npm/vue-demi@0.12.1/lib/index.iife.min.js'
        },
        {
          name: 'pinia',
          var: 'Pinia',
          path: 'https://cdn.jsdelivr.net/npm/pinia@2.0.12/dist/pinia.iife.min.js'
        }
      ]
    }),
    AutoImport({
      include: [
        /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
        /\.vue$/,
        /\.vue\?vue/, // .vue
        /\.md$/ // .md
      ],
      imports: ['pinia', 'vue-router'], // 自动导入vue和vue-router相关函数
      dts: 'src/@types/auto-import.d.ts' // 生成 `auto-import.d.ts` 全局声明
    }),

    Components({
      dirs: ['src/components'],
      directoryAsNamespace: true,
      dts: 'src/@types/components.d.ts'
    }),
    viteCompression({
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: 'gzip',
      ext: '.gz'
    })
  ],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
      '@components': resolve(__dirname, 'src/components'),
      '@utils': resolve(__dirname, 'src/utils')
    },
    extensions: ['.js', '.ts', '.tsx', '.jsx']
  },

  base: '/', // 打包路径
  // optimizeDeps: {
  //   include: ['axios']
  // },
  build: {
    sourcemap: false,
    target: 'modules',
    outDir: 'dist',
    assetsDir: 'assets',
    minify: 'terser', // 混淆器
    cssCodeSplit: true, // 如果设置为false，整个项目中的所有 CSS 将被提取到一个 CSS 文件中
    //小于此阈值的导入或引用资源将内联为 base64 编码，以避免额外的 http 请求。设置为 0 可以完全禁用此项
    assetsInlineLimit: 4096,
    //设置为 false 来禁用将构建后的文件写入磁盘
    write: true,
    //默认情况下，若 outDir 在 root 目录下，则 Vite 会在构建时清空该目录。
    emptyOutDir: true,
    //启用/禁用 brotli 压缩大小报告
    brotliSize: true,
    //chunk 大小警告的限制
    chunkSizeWarningLimit: 500,
    terserOptions: {
      compress: {
        //打包移除console
        drop_console: true,
        drop_debugger: true
      },
      output: {
        // 去掉注释内容
        comments: true
      }
    },
    //打包分包
    rollupOptions: {
      external: ['vue', 'element-plus', 'vue-router', 'vue-demi', 'pinia'],
      plugins: [
        externalGlobals({
          vue: 'Vue',
          'element-plus': 'ElementPlus',
          'vue-router': 'VueRouter',
          'vue-demi': 'VueDemi',
          pinia: 'Pinia'
        })
      ],

      output: {
        chunkFileNames: 'static/js/[name]-[hash].js',
        entryFileNames: 'static/js/[name]-[hash].js',
        assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        manualChunks(id, { getModuleInfo }) {
          // node_modules
          if (id.includes('node_modules')) {
            return 'vendor'
          }
          //  被多处引用的组件
          const reg = /(.*)\/src\/components\/(.*)/
          if (reg.test(id)) {
            const importersLen = getModuleInfo(id).importers.length
            if (importersLen > 1) {
              return 'common'
            }
          }
        }
      }
    }
  },

  server: {
    port: 4000, // 服务端口号
    open: true, // 服务启动时是否自动打开浏览器
    host: '0.0.0.0'
    // https:true,
    // proxy: {
    //   //接口代理
    //   '/api': {
    //     target: 'http://localhost:4000',
    //     changeOrigin: true,
    //     rewrite: (path) => path.replace(/^\/api/, '')
    //   }
    // }
  }
})
